// pages/order/orderInfo/orderInfo.js
const app = getApp()
import config from '../../../utils/config.js';
import util from '../../../utils/util.js';
import Toast from '../../../vant/toast/toast';
import {
  orderModel
} from '../../../models/order';
const order = new orderModel();

import {
  indexModel
} from '../../../models/index';
const index = new indexModel();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    config:config,
    nvabarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '订单详情',
      //  导航栏 中间的标题
    },
    height: app.globalData.height,
    navHeight: app.globalData.barheight,
    roleType:app.globalData.roleType,

    mid:'',      // 消息ID
    index:'',
    type:'',

    shopOrderNo:'',   // 订单编号
    newPrice:0,       // 订单总价格
    updatePrice:0,    // 改单前价格
    detail:{
      receiveUserAddress:"南山",
      receiveUserTelephone:"18219532076",
      receiveUserName:"逻辑思维",
    },
    canteenSingleOrderGroupWithGoodInfoVoList: '', // 订单内容

    date: '',//默认起始时间  
    date1: '',//默认结束时间 
    minDate: new Date().getTime()+60*60*1000,
    // maxDate: 0,
    currentDate: new Date().getTime(), 
    formatter(type, value) {
      if (type === 'seconds') {
        return '';
      }
      return value;
    },
    show: false,

    remarks:'', // 备注

    pcount: '',
    show2: false,
    pindex: 0,
    sindex: 0,
    isUnit: 0, // 是否允许小数 0否，1是
    
    // 可改单
    modifyTotal: 0, // 合计
    modifyTotalCount: 0, // 总数

    // 改单前
    orderTotalCount: 0, // 总数
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      shopOrderNo:options.id,
      mid:options.mid || '',
      index:options.index || '',
      type:options.type || '',
    })
    this.selectInfo()
    if(options.type==2){  // 由订单消息跳转过来
      if(options.state != 1){
        this.messageRead();
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      roleType:app.globalData.roleType
    })
  },

  // 详情
  selectInfo(){
    order.apiOrderDetail({shopOrderNo:this.data.shopOrderNo}, res => {
      if(res.deliveryTime){
        var currentDate = new Date(res.deliveryTime.replace(/-/g,'/')).getTime();
        var date = util.formatTimeTwo(currentDate,'Y-M-D h:m')
        this.setData({
          date: date,
          currentDate: currentDate
        })
      }
      var canteenSingleOrderGroupWithGoodInfoVoList = JSON.stringify(res.canteenSingleOrderGroupWithGoodInfoVoList)
      canteenSingleOrderGroupWithGoodInfoVoList = JSON.parse(canteenSingleOrderGroupWithGoodInfoVoList)
      this.setData({
        detail:res,
        remarks: res.remarks,
        canteenSingleOrderGroupWithGoodInfoVoList: canteenSingleOrderGroupWithGoodInfoVoList
      })
      // 合计
      this.allTotalFun()
    })
  },

  // 消息已读
  messageRead(){
    index.apiReadMessage({id:this.data.mid}, res => {
        this.updatDate();  // 更新父级页面数据
    })
  },

  // 更新父级数据
  updatDate(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];
    var readStatus = "dataList["+this.data.index+"].readStatus";
    prevPage.setData({
      [readStatus]: 1
    })
},

  // 修改改单前价格
  updateP(res){
    var list = res.singleOrderInfoVoList;
    var updatePrice = 0;
    for(var i=0;i<list.length;i++){
      var price = 0;
      var count = 0;
      if(list[i].originalGoodPrice){
        price = list[i].originalGoodPrice
      }else{
        price = list[i].price
      }
      if(list[i].originalGoodCount){
        count = list[i].originalGoodCount
      }else{
        count = list[i].goodCount
      }
      updatePrice+=price*count;
    }
    this.setData({
      updatePrice:updatePrice
    })
  },
  onSlide(e) {
    var index = e.currentTarget.dataset.trindex
    var canteenSingleOrderGroupWithGoodInfoVoList = this.data.canteenSingleOrderGroupWithGoodInfoVoList
    canteenSingleOrderGroupWithGoodInfoVoList[index].show = !canteenSingleOrderGroupWithGoodInfoVoList[index].show
    this.setData({
      canteenSingleOrderGroupWithGoodInfoVoList: canteenSingleOrderGroupWithGoodInfoVoList
    })

  },
  onSlide1(e) {
    var index = e.currentTarget.dataset.trindex
    var canteenSingleOrderGroupWithGoodInfoVoList = this.data.canteenSingleOrderGroupWithGoodInfoVoList
    canteenSingleOrderGroupWithGoodInfoVoList[index].show1 = !canteenSingleOrderGroupWithGoodInfoVoList[index].show1
    this.setData({
      canteenSingleOrderGroupWithGoodInfoVoList: canteenSingleOrderGroupWithGoodInfoVoList
    })

  },

  // 取消
  backPage(){
    wx.navigateBack()
  },

  // 确认收货
  onReceiving(){
    order.apiReceiveOrder({shopOrderNo:this.data.shopOrderNo}, res => {
      Toast.success('操作成功');
      setTimeout(function () {
        wx.navigateBack({
          delta: 1,
        })
      }, 1000);
    })
  },

  // 确认订单
  // onConfirm(){
  //   order.apiConfirmOrder({shopOrderNo:this.data.shopOrderNo}, res => {
  //     Toast.success('操作成功');
  //     setTimeout(function () {
  //       wx.navigateBack({
  //         delta: 1,
  //       })
  //     }, 1000);
  //   })
  // },

  // 取消订单
  onCancel(){
    order.apiCancelOrder({shopOrderNo:this.data.shopOrderNo}, res => {
      Toast.success('操作成功');
      setTimeout(function () {
        wx.navigateBack({
          delta: 1,
        })
      }, 1000);
    })
  },

  // 导出
  onExport() {
    order.exportOrder(this.data.shopOrderNo, res => {
      const filePath = res.tempFilePath
      wx.openDocument({
        filePath: filePath,
        showMenu: true,
        success: function (res) {
          console.log('打开文档成功')
        }
      })
    })
  },

  // 商品详情
  onLink: util.throttle(function(e){
    console.log(e)
    var productId = e.currentTarget.dataset.productid;
    if (productId) 
      wx.navigateTo({
        url: '/pages/commodity/commodityInfo/commodityInfo?productId=' + productId+'&addt=1',
      })
  }),

  // 再次购买
  onAgin: util.throttle(function(e) {
    order.carAddBatch({
      shopOrderNo: this.data.shopOrderNo
    },function(res){
      if(res.code == 200){
        wx.switchTab({
          url: '/pages/statistics/statistics',
        })
      }else{
        util.msg(res.msg)
      }
    })
  }),

  // 交货日期选择  
  onDeliveryTime(e) {
    this.setData({
      show: true
    })
  },
  onConfirm(event) {
    var date = util.formatTimeTwo(event.detail,'Y-M-D h:m')
    var minDate1 = event.detail

    this.setData({
      currentDate: event.detail,
      date: date,
      show: false,
      // minDate1: minDate1
    });
  },
  onCancel0(){
    this.setData({
      show: false
    })
  },
  // 备注
  onRemarks(event){
    this.setData({
      remarks: event.detail
    })
  },

  // 修改订单
  onModify: util.throttle(function(e) {
    var flag = false;
    const params = {
      deliveryTime: this.data.date?(this.data.date+':00'):'',
      goodList: [],
      remarks: this.data.remarks,
      shopOrderNo: this.data.shopOrderNo
    }
    let oldData = []
    for(const iold of this.data.detail.canteenSingleOrderGroupWithGoodInfoVoList){
      for(const jold of iold.singleOrderInfoVoList){
        oldData.push(jold.goodCount)
      }
    }
    let newData = []
    for(const inew of this.data.canteenSingleOrderGroupWithGoodInfoVoList){
      for(const jnew of inew.singleOrderInfoVoList){
        newData.push(jnew.goodCount)
      }
    }
    // console.log(JSON.stringify(oldData) !== JSON.stringify(newData))
    for(const i of this.data.canteenSingleOrderGroupWithGoodInfoVoList){
      for(const j of i.singleOrderInfoVoList){
        params.goodList.push({
          goodCount: j.goodCount,
          goodId: j.goodId,
          stallId: j.stallId
        })
      }
    }
    if(JSON.stringify(oldData) !== JSON.stringify(newData)){ // 判断是否改单了
      flag = flag||true
    }
    
    var date;
    if(this.data.detail.deliveryTime) {
      var currentDate = new Date(this.data.detail.deliveryTime.replace(/-/g,'/')).getTime();
      date = util.formatTimeTwo(currentDate,'Y-M-D h:m')
    }
    if(this.data.date != date){ // 交货日期未修改
      flag = flag||true
    }
    if(this.data.remarks != this.data.detail.remarks){ // 买家备注未修改
      flag = flag||true
    }
    if(!flag){
      util.msg('未修改信息');
      return;
    }
    order.updateOrder(JSON.stringify(params),function(res){
      Toast.success('操作成功');
      setTimeout(function () {
        wx.navigateBack({
          delta: 1,
        })
      }, 1000);
    })
  }),
  // 操作/改单
  onPrice(e){
    this.data.pindex = e.currentTarget.dataset.index
    this.data.sindex = e.currentTarget.dataset.sindex
    this.data.isUnit = e.currentTarget.dataset.unit // 是否允许小数
    var canteenSingleOrderGroupWithGoodInfoVoList = this.data.canteenSingleOrderGroupWithGoodInfoVoList
    // var pprice = goodsList[index].price
    var pcount = canteenSingleOrderGroupWithGoodInfoVoList[this.data.pindex].singleOrderInfoVoList[this.data.sindex].goodCount
    this.setData({
      // pprice: pprice,
      pcount: pcount,
      show2: true
    })
  },
  onPCount(e){
    this.setData({
      pcount: e.detail
    })
  },
  onCancel2(){
    this.setData({
      show2: false
    })
  },
  onConfirm2(event){
    if(!this.data.pcount){
      util.msg('请输入数量')
      event.detail.dialog.stopLoading(); // 可以通过 stopLoading() 在外部关闭按钮的 loading
      return
    }
    var canteenSingleOrderGroupWithGoodInfoVoList = this.data.canteenSingleOrderGroupWithGoodInfoVoList
    canteenSingleOrderGroupWithGoodInfoVoList[this.data.pindex].singleOrderInfoVoList[this.data.sindex].goodCount = this.data.pcount
    // var detail = this.data.detail
    // detail.canteenSingleOrderGroupWithGoodInfoVoList = canteenSingleOrderGroupWithGoodInfoVoList
    this.setData({
      canteenSingleOrderGroupWithGoodInfoVoList: canteenSingleOrderGroupWithGoodInfoVoList,
      show2: false
      // detail: detail
    })
    this.allTotalFun() // // 重新计算合计(可改单)
  },
  // 重新计算合计(可改单)
  allTotalFun() {
    var canteenSingleOrderGroupWithGoodInfoVoList = this.data.canteenSingleOrderGroupWithGoodInfoVoList
    var modifyTotal = 0, modifyTotalCount = 0, orderTotalCount = 0
    for(var p=0;p<canteenSingleOrderGroupWithGoodInfoVoList.length;p++){
        for(var k=0;k<canteenSingleOrderGroupWithGoodInfoVoList[p].singleOrderInfoVoList.length;k++){
          modifyTotal += Number(canteenSingleOrderGroupWithGoodInfoVoList[p].singleOrderInfoVoList[k].goodCount) * Number(canteenSingleOrderGroupWithGoodInfoVoList[p].singleOrderInfoVoList[k].price)
          modifyTotalCount += Number(canteenSingleOrderGroupWithGoodInfoVoList[p].singleOrderInfoVoList[k].goodCount)
          orderTotalCount += Number(canteenSingleOrderGroupWithGoodInfoVoList[p].singleOrderInfoVoList[k].originalGoodCount?canteenSingleOrderGroupWithGoodInfoVoList[p].singleOrderInfoVoList[k].originalGoodCount:canteenSingleOrderGroupWithGoodInfoVoList[p].singleOrderInfoVoList[k].goodCount)
        }
    }
    if(this.data.detail.updateStatus == 1){ // 可改单，改单前的总数
      this.setData({
        orderTotalCount: orderTotalCount
      })
    }
    this.setData({
      modifyTotal: modifyTotal,
      modifyTotalCount: modifyTotalCount
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})